<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:c="livcos.org/ns/cosmos"
  xmlns:da="livcos.org/ns/cosmos/data-access"
  xmlns:p="livcos.org/ns/cosmos/proxy"
  xmlns:f="livcos.org/ns/xslt/function"
  xmlns:xs="http://www.w3.org/2001/XMLSchema"
  exclude-result-prefixes="c p da f xs">
  
	<xsl:import href="../../../style/base.xsl"/>
	<xsl:import href="../../../style/mime.xsl"/>
	
  <xsl:template match="c:*" mode="content">
    <xsl:param name="prefix"/>
    <xsl:variable name="pathNodes" select="ancestor-or-self::*[position() &lt; last()]"/>
    <xsl:variable name="uri" select="string-join(for $n in $pathNodes return local-name($n), '/')"/>
    <xsl:variable name="src">
      <xsl:if test="$prefix"><xsl:value-of select="$prefix"/>/</xsl:if>
      <xsl:value-of select="$uri"/>
    </xsl:variable>
    <xsl:variable name="ext" select="f:file-ext(.)"/>
    <resource ref="{$src}.{$ext}" out="{$uri}.{$ext}"/>
  </xsl:template>
  
  <xsl:template match="c:*[c:*]" mode="content">
    <xsl:param name="prefix"/>
    <xsl:apply-templates select="c:*" mode="content">
      <xsl:with-param name="prefix" select="$prefix"/>
    </xsl:apply-templates>
  </xsl:template>
  
	<xsl:function name="f:file-ext" as="xs:string">
		<xsl:param name="obj"/>
		<xsl:variable name="da" select="$obj/da:file[@name = local-name($obj)]"/>
		<xsl:choose>
			<xsl:when test="$da/@ext">
				<xsl:value-of select="$da/@ext"/>
			</xsl:when>
			<xsl:otherwise>
				<xsl:call-template name="mime2file">
					<xsl:with-param name="mimeType">
						<xsl:choose>
							<xsl:when test="$obj/data/@type">
								<xsl:value-of select="$obj/data/@type"/>
							</xsl:when>
							<xsl:when test="$obj/p:stream/@content-type">
								<xsl:value-of select="$obj/p:stream/@content-type"/>
							</xsl:when>
							<xsl:otherwise>
								<xsl:value-of select="$obj/@content-type"/>
							</xsl:otherwise>
						</xsl:choose>
					</xsl:with-param>
				</xsl:call-template>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:function>
	
</xsl:stylesheet>
